<script setup lang="ts">
import { ref, defineEmits, computed, watch, onMounted, nextTick } from 'vue';
import { useBooleanStore } from '@/store';
import { getName, getUserJob, getUserUnits } from '@/utils/auth';
import { Modal, Notification } from '@arco-design/web-vue';
import {
  searchBeputMaterial,
  updateRepair,
  receiveGoingOn,
  searchAwaitStorage,
  materialReceipt,
  PWacdfimnoorrss,
  searchWorkbinXl,
  bufferBoxWarehousing,
  backDeliverys,
  typeWarehousing,
} from '@/api/material-receipt';
import { isString } from 'lodash';

const emit = defineEmits(['updateArray', 'updateBottomTable']);
const booleanStore = useBooleanStore();
const hStyle = ref({
  'background-color': booleanStore.color,
  'border-radius': booleanStore.borderRadius,
});
// 表单查询数据
const pageSize = ref<number>(30);
const pageNumber = ref<number>(1);
const current = ref<number>(1);
const scanCode = ref<string>('');
const showBoxTm = ref<string>('');
const scanInput = ref<any>('');
const hcxScanNum = ref<boolean>(false);
// 当前缓存箱里面的物料
const materialList = ref<any[]>([]);
// 缓存箱的物料条码结合
const barcodeList = ref<any[]>([]);
const materialCard = ref<boolean>(false);
const passwordValue = ref<string>('');
const visible = ref<boolean>(false);
const visibleTick = ref<boolean>(false);
const disabled = ref<boolean>(false);
const countBlue = ref<number>(0);
// 9005扫码两次参数
const submitNum = ref<number>(0);
// 9002扫码两次参数
const returnNum = ref<number>(0);
// 缓存箱里的物料是否全部确认
const isCheckMarterial = ref<boolean>(false);
// 物料状态

const materialStatus = ref<any>('');
const bigMlist = ref<any[]>([]);
const bigM = ref<boolean>(false);
// 发送搜索数据
const flowQueryData = ref({
  pageSize: computed(() => pageSize.value),
  currentPage: computed(() => pageNumber.value),
});
const scanHint = computed(() => {
  switch (current.value) {
    case 2:
      return '请扫描物料条码,当前进度流程为:物料确认,请勿扫缓存箱编码';
    case 3:
      return '请扫描入库确认条码,当前进度流程为:物料入库,请勿扫缓存箱编码';
    case 4:
      return '请扫描回库确认条码,当前进度流程为:缓存箱入库,请勿扫缓存箱编码';
    default:
      return '请勿重复扫缓存箱编码';
  }
});
const newData: any = ref<any[]>([]);
// 刷新已入库物料列表
function bottomTableSearch() {
  emit('updateBottomTable');
}
// 表格数据
async function handleSearch() {
  newData.value = await searchBeputMaterial(flowQueryData.value);
  emit('updateArray', newData.value);
  bottomTableSearch();
}
// 物料回退
function resetCode() {
  if (
    !booleanStore.materialList[0]?.value ||
    booleanStore.materialList[0]?.value.length === 0
  ) {
    Notification.error({
      title: '错误',
      content: '请您至少选择一条数据',
      closable: true,
    });
    return;
  }
  visibleTick.value = true;
}
// 确定回退
async function handleTrue() {
  const dataInfo = ref<any[]>([]);
  booleanStore.materialList[0].value.forEach((item: any) => {
    const res: any = newData.value.list.find(
      (item_: any) => item_.PAGEHELPER_ROW_ID === item
    );
    if (res) {
      dataInfo.value.push(res);
    }
  });

  console.log(dataInfo.value);
  const data: any = await backDeliverys(dataInfo.value);
  if (data.retCode === '200') {
    Notification.success({
      title: '成功',
      content: data.message,
      closable: true,
    });
  } else {
    Notification.error({
      title: '错误',
      content: data.message,
      closable: true,
    });
  }
  // 清空中间操作的数据
  dataInfo.value = [];
  // 清空选择的数据
  booleanStore.toggleBool4(6);
  // 更新数据
  handleSearch();
  // 关闭弹框
  visibleTick.value = false;
}

// 物料漏扫
async function repairMaterial() {
  const info: any = ref({
    workbinCode: computed(() => showBoxTm.value),
  });
  const data = await updateRepair(info.value);
  if (data.retCode === '200') {
    Notification.success({
      title: '成功',
      content: data.message,
      closable: true,
    });
  } else {
    Notification.error({
      title: '错误',
      content: data.message,
      closable: true,
    });
  }
}

// 继续执行
async function taskGoOn() {
  const data = await receiveGoingOn({});
  if (data.retCode === '200') {
    Notification.success({
      title: '成功',
      content: data.message,
      closable: true,
    });
  } else {
    Notification.error({
      title: '错误',
      content: data.message,
      closable: true,
    });
  }
}

async function handleClose() {
  if (current.value === 2) {
    passwordValue.value = '';
    visible.value = true;
  } else {
    Notification.warning({
      title: '提示',
      content: '当前物料已全部确认完成',
      closable: true,
    });
  }
}
// 一键确定的功能
async function handleOk() {
  const info: any = ref({
    passWord: computed(() => passwordValue.value),
  });
  const data = await PWacdfimnoorrss(info.value);
  if (data.retCode === '200') {
    Notification.success({
      title: '成功',
      content: data.retMsg,
      closable: true,
    });
    barcodeList.value = [];
    for (let i = 0; i < materialList.value.length; i += 1) {
      materialList.value[i].isMaterial = '已确认';
      countBlue.value = materialList.value.length;
      barcodeList.value.push(materialList.value[i].barcode);
    }
    current.value += 1;
    // 物料全部确认
    isCheckMarterial.value = true;
    visible.value = false;
    await nextTick(() => {
      scanInput.value.focus();
    });
  } else {
    Notification.error({
      title: '错误',
      content: data.retMsg,
      closable: true,
    });
  }
}
// 获取大物件信息
async function getBigMList() {
  const data: any = await searchWorkbinXl({});
  bigMlist.value = data.responseBody;
}

// 缓存箱扫码
async function hcxScan() {
  try {
    disabled.value = true;
    showBoxTm.value = scanCode.value;
    if (showBoxTm.value === '') {
      Notification.error({
        title: '错误',
        content: '条码不能为空！',
        closable: true,
      });
    } else {
      const info = {
        workbinCode: showBoxTm.value,
      };
      const data = await searchAwaitStorage(info);
      if (data.retCode === '200') {
        hcxScanNum.value = true;
        current.value += 1;
        materialList.value = data.responseBody;
        materialList.value.forEach((item: any) => {
          item.isMaterial = '未确认';
        });
      } else {
        Notification.error({
          title: '错误',
          content: data.message,
          closable: true,
        });
      }
    }
  } catch (e) {
    console.log(`查找缓存箱数据:${e}`);
    Notification.error({
      title: '错误',
      content: '查找缓存箱失败',
      closable: true,
    });
  } finally {
    disabled.value = false;
    scanCode.value = '';
    await nextTick(() => {
      scanInput.value.focus();
    });
  }
}
// 物料入库
async function materialHouse() {
  try {
    disabled.value = true;
    booleanStore.toggleBool(0);
    // 用户名
    const name = getName() || '';
    // 工号
    const workId = getUserJob() || '';
    // 部门
    const units = getUserUnits();
    const loginIngo = name + workId;
    const loginBm = units;
    const info: any = ref({
      account: loginIngo,
      departid: loginBm,
      planDTOs: computed(() => materialList.value),
      workbinCode: computed(() => showBoxTm.value),
      barcodes: computed(() => barcodeList.value),
    });
    const data = await materialReceipt(info.value);
    if (data.retCode === '200') {
      Notification.success({
        title: '成功',
        content: data.message,
        closable: true,
      });
      handleSearch();
      bottomTableSearch();
    } else {
      Notification.error({
        title: '错误',
        content: data.message,
        closable: true,
      });
      handleSearch();
    }
  } catch (e) {
    console.log(`物料入库报错:${e}`);
    Notification.error({
      title: '错误',
      content: '物料入库失败',
      closable: true,
    });
  } finally {
    booleanStore.toggleBool(0);
    scanCode.value = '';
    nextTick(() => {
      scanInput.value.focus();
    });
    disabled.value = false;
    current.value += 1;
    // 物料清空
    materialList.value = [];
    // 判断物料是否全部确认关闭
    isCheckMarterial.value = false;
    // 物料确认框关闭
    materialCard.value = false;
    // 已确认物料清零
    countBlue.value = 0;
  }
}

// 缓存箱回库
async function handleHcxBack() {
  try {
    disabled.value = true;
    booleanStore.toggleBool(0);
    const info = {
      workbinCode: showBoxTm.value,
    };
    const data: any = await bufferBoxWarehousing(info);
    if (data.retCode === '200') {
      Notification.success({
        title: '成功',
        content: data.message,
        closable: true,
      });
    } else {
      Notification.error({
        title: '错误',
        content: data.message,
        closable: true,
      });
    }
  } catch (error) {
    console.log(`缓存箱回库报错:${error}`);
    Notification.error({
      title: '失败',
      content: '缓存箱回库失败，请手动回库',
      closable: true,
    });
  } finally {
    booleanStore.toggleBool(0);
    disabled.value = false;
    scanCode.value = '';
    nextTick(() => {
      scanInput.value.focus();
    });
    current.value = 1;
    submitNum.value = 0;
    returnNum.value = 0;
  }
}

// 确认零件物料
function checkPart(barCode: any) {
  const exists = materialList.value.some((item: any) =>
    item.barcode.includes(barCode)
  );
  if (exists) {
    materialList.value.forEach((item: any) => {
      if (item.barcode === barCode) {
        if (item.isMaterial !== '已确认') {
          barcodeList.value.push(item.barcode);
          item.isMaterial = '已确认';
          countBlue.value += 1;
          Notification.success({
            title: '成功',
            content: `物料条码为${barCode}的物料确认完毕`,
            closable: true,
          });
          if (countBlue.value === materialList.value.length) {
            current.value += 1;
          }
        } else {
          Notification.error({
            title: '失败',
            content: '该物料已经确认完毕',
            closable: true,
          });
        }
      }
    });
  } else {
    Notification.error({
      title: '失败',
      content: '请扫相对应的零件条码',
      closable: true,
    });
  }
  scanCode.value = '';
  nextTick(() => {
    scanInput.value.focus();
  });
}

// 确认成品物料
function checkFinish(certificate: any) {
  const exists = materialList.value.some((item: any) =>
    item.barcode.includes(certificate)
  );
  if (exists) {
    materialList.value.forEach((item: any) => {
      if (item.barcode === certificate) {
        if (item.isMaterial === '已确认') {
          Notification.error({
            title: '失败',
            content: '该物料已经确认完毕',
            closable: true,
          });
        } else {
          barcodeList.value.push(item.barcode);
          item.isMaterial = '已确认';
          countBlue.value += 1;
          Notification.success({
            title: '成功',
            content: `物料条码为${certificate}的物料确认完毕`,
            closable: true,
          });
          scanCode.value = '';
          nextTick(() => {
            scanInput.value.focus();
          });
          if (countBlue.value === materialList.value.length) {
            current.value += 1;
          }
        }
      }
    });
  } else {
    Notification.error({
      title: '失败',
      content: '请扫相对应的成品条码',
      closable: true,
    });
  }
  scanCode.value = '';
  nextTick(() => {
    scanInput.value.focus();
  });
}

// 确认标准件物料
function checkStandard(standardCode: any) {
  const exists = materialList.value.some(
    (item: any) => {
      const barcodeMatch =
      isString(item.barcode) && isString(standardCode) && item.barcode.includes(standardCode);
    const ckBarcodeMatch =
      isString(item.ckBarcode) && isString(standardCode) && item.ckBarcode.includes(standardCode);

    return barcodeMatch || ckBarcodeMatch;
});
  if (exists) {
    materialList.value.forEach((item: any) => {
      if (item.barcode === standardCode) {
        if (item.isMaterial !== '已确认') {
          barcodeList.value.push(item.barcode);
          item.isMaterial = '已确认';
          countBlue.value += 1;
          if (countBlue.value === materialList.value.length) {
            current.value += 1;
          }
          Notification.success({
            title: '成功',
            content: `物料条码为${standardCode}的物料确认完毕`,
            closable: true,
          });
        } else {
          Notification.error({
            title: '失败',
            content: '该物料已经确认完毕',
            closable: true,
          });
        }
      }
    });
  } else {
    Notification.error({
      title: '失败',
      content: '请扫相对应的标准件条码',
      closable: true,
    });
  }
  scanCode.value = '';
  nextTick(() => {
    scanInput.value.focus();
  });
}

// 通过AO一键确认
function checkStandardAll(aoNo: any) {
  const exists = materialList.value.some(
    (item: any) =>
      item.aoCode.includes(aoNo)
  );
  if (exists) {
    materialList.value.forEach((item: any) => {
      if (item.aoCode === aoNo) {
        if (item.isMaterial !== '已确认') {
          barcodeList.value.push(item.barcode);
          item.isMaterial = '已确认';
          countBlue.value += 1;
          if (countBlue.value === materialList.value.length) {
            current.value += 1;
          }
          Notification.success({
            title: '成功',
            content: `AO编码为${aoNo}的物料确认完毕`,
            closable: true,
          });
        } else {
          Notification.error({
            title: '失败',
            content: '该物料已经确认完毕',
            closable: true,
          });
        }
      }
    });
  } else {
    Notification.error({
      title: '失败',
      content: '请扫相对应的标准件条码',
      closable: true,
    });
  }
  scanCode.value = '';
  nextTick(() => {
    scanInput.value.focus();
  });
}

// 扫码操作
async function scanSubmit() {
  try {
    // 如果缓存箱号为空且扫码长度不为12位
    if (showBoxTm.value === '' && scanCode.value.length !== 12) {
      Notification.error({
        title: '失败',
        content: '请您先扫缓存箱编码',
        closable: true,
      });
      scanCode.value = '';
      nextTick(() => {
        scanInput.value.focus();
      });
      return;
    }
    // 条码为缓存箱条码
    if (
      scanCode.value.length === 12 &&
      (scanCode.value.indexOf('11208003') === 0 ||
        scanCode.value.indexOf('31208003') === 0)
    ) {
      if (hcxScanNum.value) {
        Notification.error({
          title: '失败',
          content: scanHint.value,
          closable: true,
        });
        scanCode.value = '';
        await nextTick(() => {
          scanInput.value.focus();
        });
      } else {
        // 缓存箱存码
        hcxScan();
      }
    } else if (scanCode.value === '9005' || scanCode.value === '90059005') {
      if (submitNum.value === 1) {
        if (isCheckMarterial.value) {
          materialHouse();
          submitNum.value += 1;
        } else {
          submitNum.value = 0;
          Notification.error({
            title: '失败',
            content: '物料未全部确认！',
            closable: true,
          });
          scanCode.value = '';
          nextTick(() => {
            scanInput.value.focus();
          });
        }
      } else if (submitNum.value > 1) {
        Notification.error({
          title: '失败',
          content: '已经扫码9005了,请不要重复扫码',
          closable: true,
        });
        scanCode.value = '';
        nextTick(() => {
          scanInput.value.focus();
        });
      } else {
        // scanCode.value = '';
        nextTick(() => {
          scanInput.value.focus();
        });
        submitNum.value += 1;
      }
    } else if (scanCode.value === '9002' || scanCode.value === '90029002') {
      if (submitNum.value > 1) {
        returnNum.value += 1;
        if (returnNum.value === 2) {
          // 缓存箱回库
          handleHcxBack();
          hcxScanNum.value = false;
          showBoxTm.value = '';
        } else {
          // scanCode.value = '';
          nextTick(() => {
            scanInput.value.focus();
          });
          // console.log(returnNum.value);
        }
      } else {
        Notification.error({
          title: '失败',
          content: '请先物料入库执行保存',
          closable: true,
        });
        scanCode.value = '';
        nextTick(() => {
          scanInput.value.focus();
        });
      }
    } else {
      const data: any = await typeWarehousing({
        message: scanCode.value.toString(),
      });
      if (data.retCode === '200') {
        if (data.responseBody.materialType === 'F') {
          // 扫码条码是否成品 F
          checkFinish(data.responseBody.certificate);
        } else if (data.responseBody.materialType === 'Z') {
          // 扫码条码是否标准件 Z
          if (data.responseBody.aoNo !== '') {
            checkStandardAll(data.responseBody.aoNo);
          } else {
            checkStandard(data.responseBody.standardCode);
          }
        } else if (data.responseBody.materialType === 'M') {
          // 零件 M
          checkPart(data.responseBody.barCode);
        }
      } else {
        Notification.error({
          title: '获取物料入库类型错误',
          content: data.message,
          closable: true,
        });
      }
    }
  } catch (e) {
    console.log(`报错数据: ${e}`);
    scanCode.value = '';
    nextTick(() => {
      scanInput.value.focus();
    });
  }
}
function showMaterialCard() {
  materialCard.value = !materialCard.value;
}
function certainClean() {
  materialList.value = [];
}
function cleanMaterialList() {
  Modal.warning({
    title: '警告',
    content: '确定要清除数据吗，清除后无法恢复数据,只能重新扫描',
    hideCancel: false,
    onOk: certainClean,
  });
}
onMounted(() => {
  nextTick(() => {
    scanInput.value.focus();
  });
  handleSearch();
  getBigMList();
});
function lookGKLog() {
  booleanStore.toggleBool2(4);
}
// 监听分页
watch([() => booleanStore.pageNum, () => booleanStore.pageSize], () => {
  if (booleanStore.num5 === 8) {
    pageNumber.value = booleanStore.pageNum;
    pageSize.value = booleanStore.pageSize;
    handleSearch();
  }
});

watch(
  materialList,
  () => {
    if (materialList.value.length > 0) {
      materialCard.value = true;
    }
  },
  { deep: true }
);
// 当全部的物料都确认后可以进行下一步
watch(countBlue, () => {
  if (countBlue.value === materialList.value.length && countBlue.value !== 0) {
    isCheckMarterial.value = true;
  }
});
</script>

<template>
  <a-card :header-style="hStyle" :bordered="false">
    <template #title>
      <div class="font">流程进度</div>
    </template>
    <a-steps type="arrow" small changeable :current="current">
      <a-step>缓存箱扫码(扫描缓存箱条码)</a-step>
      <a-step>物料确认(扫描物料条码)</a-step>
      <a-step>物料入库(扫描确认条码)</a-step>
      <a-step>缓存箱回库(扫描回库条码)</a-step>
    </a-steps>
  </a-card>
  <a-card :header-style="hStyle" :bordered="false">
    <template #title>
      <div class="font">待入库物料列表</div>
    </template>
    <div>
      <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
        <a-col :span="6">
          <div>
            <a-input
              ref="scanInput"
              v-model="scanCode"
              placeholder="请输入缓存箱/托盘码/条码"
              size="large"
              :disabled="disabled"
              @keyup.enter="scanSubmit()"
            >
              <template #prefix>
                <icon-info-circle size="13" :style="{ fontSize: '20px' }" />
              </template>
            </a-input>
          </div>
        </a-col>
        <a-col :span="12">
          <a-button type="primary" size="large" @click="resetCode"
            >回退交接单</a-button
          >
          <a-button
            type="primary"
            class="btn-reset"
            size="large"
            @click="lookGKLog()"
            >查看缓存箱</a-button
          >
          <a-button
            type="primary"
            class="btn-reset"
            size="large"
            @click="repairMaterial()"
            >物料漏扫</a-button
          >
          <a-button
            type="primary"
            class="btn-reset"
            size="large"
            @click="taskGoOn()"
            >继续执行</a-button
          >
          <a-button
            class="btn-reset"
            type="primary"
            size="large"
            @click="handleSearch()"
            >刷新数据
          </a-button>
          <!-- <a-button
          class="btn-reset"
          type="primary"
          size="large"
          @click="showMaterialCard()"
        >
          物料确认窗格
        </a-button>
        <a-button
          class="btn-reset"
          type="primary"
          size="large"
          @click="cleanMaterialList()"
        >
          清除物料数据
        </a-button> -->
        </a-col>
      </a-row>
    </div>
  </a-card>
  <a-card v-show="materialCard">
    <div class="btn-div">
      <a-button type="primary" @click="handleClose">一键确认</a-button>
      <span style="margin-left: 10px"
        >已扫码：<span
          ><b>{{ countBlue }}</b></span
        ></span
      >
      <span style="margin-left: 3px"
        >总数：<span
          ><b>{{ materialList.length }}</b></span
        ></span
      >
    </div>
    <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
      <a-col v-for="(value, index) in materialList" :key="index" :span="6">
        <a-card :style="{ width: '360px' }" title="待入库物料信息">
          <a-list size="small" :split="false">
            <a-list-item
              >物料状态：<span
                ref="materialStatus"
                :class="{ 'font-color': value.isMaterial === '已确认' }"
                >{{ value.isMaterial }}</span
              ></a-list-item
            >
            <a-list-item
              >条码：<span style="font-weight: bold">{{
                value.barcode
              }}</span></a-list-item
            >
            <a-list-item
              >合格证：<span style="font-weight: bold">{{
                value.mesCheckQualiticationId
              }}</span></a-list-item
            >
            <a-list-item>AO号：{{ value.aoCode }}</a-list-item>
            <a-list-item>限用架次：{{ value.xLimitLotNo }}</a-list-item>
            <a-list-item>起始架次：{{ value.startLotNo }}</a-list-item>
            <a-list-item>截止架次：{{ value.endLotNo }}</a-list-item>
            <a-list-item>版本号：{{ value.version }}</a-list-item>
            <a-list-item>工艺状态号：{{ value.processStatusNo }}</a-list-item>
            <a-list-item>最长保管期：{{ value.maxStorageDate }}</a-list-item>
            <a-list-item>复试期：{{ value.retestData }}</a-list-item>
            <a-list-item>
              <div class="div-flex"
                ><div>移交数量：{{ value.deliveryQty }}</div>
                <div class="div-right"
                  >物料数量：<a-input
                    v-model="value.storageQty"
                    class="input-class"
                /></div>
              </div>
            </a-list-item>
            <a-list-item>图号：{{ value.itemCode }}</a-list-item>
            <a-list-item>质量编号/件号：{{ value.qualityCode }}</a-list-item>
            <a-list-item>成品型号：{{ value.mProductNumber }}</a-list-item>
            <a-list-item>质量编号/件号：{{ value.qualityCode }}</a-list-item>
            <a-list-item v-if="bigM"
              >大件库位：<a-select v-model="value.wmsLocatorId">
                <a-option
                  v-for="item in bigMlist"
                  :key="item.wmsLocatorId"
                  :value="item.wmsLocatorId"
                >
                  {{ item.locatorNo }}
                </a-option>
              </a-select>
            </a-list-item>
          </a-list>
        </a-card>
      </a-col>
      <a-modal
        :visible="visible"
        unmount-on-close
        @ok="handleOk"
        @cancel="visible = false"
      >
        <template #title> 确认信息填写 </template>
        <div class="drawer-class">
          <a-input-password
            v-model="passwordValue"
            placeholder="请输入密码"
            @press-enter="handleOk"
          ></a-input-password>
        </div>
      </a-modal>
    </a-row>
    <a-modal
      v-model:visible="visibleTick"
      @ok="handleTrue"
      @cancel="visibleTick = false"
    >
      <template #title> 回退交接单 </template>
      <div>是否确认回退数据?</div>
    </a-modal>
  </a-card>
</template>

<style scoped>
.margin-top {
  margin-top: 10px;
}
.btn-group {
  float: right;
  margin-top: 15px;
}

.btn-reset {
  margin-left: 10px;
}
.font {
  font-size: 20px;
  color: black;
  font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
    Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
.div-tips {
  align-items: center;
  text-align: center;
  color: #999;
}
.btn-div {
  margin-bottom: 10px;
}

.div-flex {
  display: flex;
  justify-content: start;
  align-items: center;
  white-space: nowrap;
}

.div-flex .div-right {
  margin-left: 10px;
}

.div-flex .div-right .input-class {
  width: 30%;
}

.drawer-class {
  width: 80%;
}
.font-color {
  font-size: 16px;
  color: blue;
}
</style>
